package handler

import (
	"Gin/api/request"
	"Gin/global/model"
	"Gin/global/pkg"
	"Serve/VideoSrv"
	"context"
	"github.com/gin-gonic/gin"
	"net/http"
	"path"
	"strings"
)

func VideoPush(c *gin.Context) {
	var VideoPushRequest request.VideoPushRequest
	if err := c.ShouldBind(&VideoPushRequest); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": err.Error(),
		})
		return
	}
	file, m, err := c.Request.FormFile("video")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": err.Error(),
		})
		return
	}
	ext := path.Ext(m.Filename)
	if !strings.Contains(".mp4.Avi.Mov", ext) {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "文件格式不支持",
			"data":    ext,
		})
		return
	}
	if m.Size > 2<<30 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "文件过大",
			"data":    m.Size,
		})
	}
	video_url, err := pkg.Upload(file, m)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": err.Error(),
		})
		return
	}
	file2, m2, err := c.Request.FormFile("image")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": err.Error(),
		})
		return
	}
	image_url, err := pkg.Upload(file2, m2)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": err.Error(),
		})
		return
	}
	push, err := model.VideoClient.VideoPush(context.Background(), &VideoSrv.VideoPushRequest{
		Title:    VideoPushRequest.Title,
		Class:    int64(VideoPushRequest.Class),
		Des:      VideoPushRequest.Des,
		Tag:      VideoPushRequest.Tag,
		VideoUrl: video_url,
		ImageUrl: image_url,
		UserId:   int64(VideoPushRequest.UserId),
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "ok",
		"data":    push,
		"url":     video_url,
	})
}
